import { IndustryListData } from '../../../../models/industryData';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute, Router } from '@angular/router';  // 用于获取路由参数
import { UploadService } from 'src/app/services/upload.service';
import { OrganizationInfo, codeList } from 'src/app/models';
import { OrganizationService } from 'src/app/services/organization.service';
import { ExceptionHandler } from 'src/app/handler/exception.handler';


@Component({
  selector: 'zepride-edit-organization',
  templateUrl: './edit-organization.component.html',
  styleUrls: ['./edit-organization.component.less']
})
export class EditOrganizationComponent implements OnInit {
  validateForm: FormGroup;

  loading = false;
  logining = false;
  organizationInfo: OrganizationInfo = {} as OrganizationInfo;

  values: string[] = [];
  Id: string;
  postageTime = null;
  title = '新增客户';

  industryList = [];
  constructor(
    private fb: FormBuilder,
    private msg: NzMessageService,
    private route: Router,
    private activatedRoute: ActivatedRoute,
    public uploadService: UploadService,
    private organizationService: OrganizationService
  ) {
    //获取编辑需要的参数
    activatedRoute.queryParams.subscribe(queryParams => {
      this.Id = queryParams.Id;
    });
    this.validateForm = this.fb.group({
      name: ['', [Validators.required, Validators.pattern(/.*\S.*/)]],
      industry: [''],
      upstreamIndustry: [''],
      downstreamIndustry: [''],
      specialNote: [''],
      postage: [''],
      orgType: ['法人组织'],
      systemTypes: [[]]
    });
  }

  async ngOnInit() {
    if (this.Id != '0') {
      this.title = '编辑客户';
      await this.getOrganizationInfoById();
    }

    this.setValidataForm(this.organizationInfo);

    this.industryList = IndustryListData;
  }

  private setValidataForm(orgData: OrganizationInfo) {
    if (orgData) {
      if (!orgData.orgType) {
        orgData.orgType = '法人组织';
      }
      if (!orgData.systemTypes) {
        orgData.systemTypes = ['内控管理系统'];
      }
      else {
        if (!(orgData.systemTypes instanceof Array)) {
          orgData.systemTypes = [orgData.systemTypes];
        }
      }
      for (let key in orgData) {
        if (this.validateForm.controls[key]) {
          this.validateForm.controls[key].setValue(orgData[key]);
        }
      }

    }
  }

  onDateChange(result: Date[]): void {
    console.log('onChange: ', result);
    this.organizationInfo.postageTimeBegin = result[0].getTime();
    this.organizationInfo.postageTimeEnd = result[1].getTime();
  }

  //查询详情
  async getOrganizationInfoById() {
    try {
      this.organizationInfo = await this.organizationService.getOrganizationInfoById(this.Id);
      this.postageTime = [new Date(this.organizationInfo.postageTimeBegin), new Date(this.organizationInfo.postageTimeEnd)];
      console.log(this.postageTime, this.organizationInfo);
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  validateConfirmPassword(): void {
    setTimeout(() => this.validateForm.controls.confirm.updateValueAndValidity());
  }
  goBack() {
    history.go(-1);
  }
  submitForm(value: { userName: string; phone: string; password: string; organizationalCode: string; address: string }): void {
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

  onChanges(values: string[]): void {
    this.organizationInfo.province = values[0];
    this.organizationInfo.city = values[1];
    this.organizationInfo.area = values[2];
  }
  async confirm() {
    if (!this.validateForm.valid) return;
    if (this.logining) {
      return;
    }
    this.logining = true;

    try {
      this.organizationInfo.orgTree = { parentId: null };
      this.organizationInfo.status = '0'; //默认状态 正常
      for (let key in this.validateForm.controls) {
        this.organizationInfo[key] = this.validateForm.controls[key].value;
      }
      if (this.Id != '0') {
        const data = await this.organizationService.updateOrganization(this.organizationInfo);
      } else {
        this.organizationService.orgid = '';
        const data = await this.organizationService.createOrganization(this.organizationInfo);
      }
      this.msg.success(this.Id != '0' ? '编辑组织机构成功' : '添加组织机构成功');
      this.goBack();
    } catch (error) {
      ExceptionHandler.current.handleError(error);

    } finally {
      this.logining = false;
    }
  }
}
